Laravel hasManyで親レコード削除と同時に子レコード削除の書き方

migration時に$table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);と書く

AdminPostsController.php

public function edit($id)
    {
        //
        $post = Post::findOrFail($id);
        $categories = Category::lists('name', 'id')->all();
        return view('admin.posts.edit', compact('post','categories'));
    }

View: edit.blade.php

<h1>Edit Post</h1>
	{!! Form::Model($post, ['method'=>'PATCH', 'action'=>['AdminPostsController@update', $post->id], 'files'=>true]) !!}
        {{ csrf_field()}}
 
        <div class="form-group">
            {!! Form::label('title', 'Title') !!}
            {!! Form::text('title', null, ['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::label('category_id', 'Category') !!}
            {!! Form::select('category_id', $categories, null, ['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::label('photo_id', 'Photo') !!}
            {!! Form::file('photo_id', null,['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::label('body', 'Description') !!}
            {!! Form::textarea('body', null, ['class'=>'form-control', 'rows'=>3]) !!}
        </div>


        
        <div class="form-group">
            {!! Form::submit('Create Post', ['class'=>'btn btn-primary']) !!}
        </div>
    {!! Form::close() !!}

    </div>

    <div class="row">

    @include('includes.form_error')

	</div>

index.blade.php

<tr>
			  <td>{{$post->id}}</td>
			  <td><img height="50" src="{{$post->photo ? '/' . $post->photo->file : 'https://placehold.it/50x50'}}"></td>
			  <td><a href="{{route('admin.posts.edit', $post->id)}}">{{$post->user->name}}</a></td>
			  <td>{{$post->category ? $post->category->name : 'Uncategorized'}}</td>
			  <td>{{$post->title}}</td>
			  <td>{{$post->body}}</td>
			  <td>{{$post->created_at->diffForHumans()}}</td>
			  <td>{{$post->updated_at->diffForHumans()}}</td>
			</tr>

AdminPhotosController.php

public function update(Request $request, $id)
    {
        //
        $input = $request->all();

        if($file = $request['photo_id']){
            $name = time(). $file->getClientOriginalName();
            $file->move('images', $name);
            $photo = Photo::create(['file'=>$name]);

            $input['photo_id'] = $photo->id;
        }

        Auth::user()->posts()->whereId($id)->first()->update($input);

        return redirect('/admin/posts');
    }

### helper
laravel helper string functions
https://laravel.com/docs/master/helpers

string limit
https://laravel.com/docs/master/helpers#method-str-limit

 <td>{{str_limit($post->body, 10)}}</td>

### delete
edit.blade.php

{!! Form::open(['method'=>'DELETE', 'action'=>['AdminPostsController@destroy', $post->id]]) !!}
        {{ csrf_field()}}
        
        <div class="form-group">
            {!! Form::submit('Delete Post', ['class'=>'btn btn-danger col-sm-6']) !!}
        </div>
        {!! Form::close() !!}

AdminPostsController.php

public function destroy($id)
    {
        //
        $post = Post::findOrFail($id);
        unlink(public_path() . '/' .  $post->photo->file);
        $post->delete();

        return redirect('/admin/posts');
    }

### ユーザ削除するとpostsもdelete
Post migration file

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('category_id')->unsigned()->index();
            $table->integer('photo_id')->unsigned()->index();
            $table->string('title');
            $table->text('body');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

$ php artisan migrate:refresh

insert into roles (name) values (‘Administrator’);
insert into roles (name) values (‘Author’);
insert into roles (name) values (‘Subscriber’);

insert into categories (name) values (‘PHP’);
insert into categories (name) values (‘Laravel’);
insert into categories (name) values (‘JavaScript’);
insert into categories (name) values (‘Photoshop’);

update posts set user_id=10 where id=1;
update users set role_id=1 where id=1;

update posts set user_id=2 where id=2;

AdminUserController.php

public function destroy($id)
    {
        //
        $user = User::findOrFail($id);

        if($user->photo !== NULL){
            unlink(public_path() ."/". $user->photo->file);
        }
        $user->delete();

        Session::flash('deleted_user', 'The user has benn deleted');
        return redirect('/admin/users');
    }

edit.blade.php

<div class="col-sm-6">
		<img src="{{$post->photo ? $post->photo->file : 'https://placehold.it/400x400'}}" alt="" class="img-responsive">

	</div>

実際のアプリケーションでは、ユーザはsoftdeleteとして、更にユーザを削除しても、hasManyの子レコードは残したいケースが多いように思いますが、一緒に削除も可能です。

helperはstr_limit以外にも使えそうなものは使いたい。